﻿using System.Web.Mvc;
using Nop.Plugin.Widgets.ShoppingMail.Models;
using Nop.Services.Configuration;
using Nop.Web.Framework.Controllers;
using System;
using System.Linq;
using System.Globalization;
using Nop.Core.Domain.Orders;
using Nop.Core;
using Nop.Services.Orders;
using Nop.Services.Logging;
using Nop.Services.Catalog;
using System.Text;
using Nop.Core.Domain;

namespace Nop.Plugin.Widgets.ShoppingMail.Controllers
{
    public class WidgetsShoppingMailController : Controller
    {
        private readonly IWorkContext _workContext;
        private readonly ISettingService _settingService;
        private readonly IOrderService _orderService;
        private readonly ICategoryService _CategoryService;
        private readonly ILogger _logger;
        private readonly IWebHelper _webHelper;
        private readonly ShoppingMailSettings _ShoppingMailSettings;
        private readonly StoreInformationSettings _storeInformationSettings;

        CultureInfo usCulture = new CultureInfo("en-US");
        internal const string HTMLADD_KEY = "Nop.ShoppingMail.HtmlAd";

        public WidgetsShoppingMailController(IWorkContext workContext, ISettingService settingService,
            IOrderService orderService,
            ICategoryService CategoryService,
            ILogger logger, IWebHelper webHelper,
            ShoppingMailSettings ShoppingMailSettings, StoreInformationSettings storeInformationSettings)
        {
            this._workContext = workContext;
            this._settingService = settingService;
            this._orderService = orderService;
            this._CategoryService = CategoryService;
            this._logger = logger;
            this._webHelper = webHelper;
            this._ShoppingMailSettings = ShoppingMailSettings;
            this._storeInformationSettings = storeInformationSettings;
        }

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure()
        {
            var model = new ConfigurationModel();
            model.IncludeBannerInMails = _ShoppingMailSettings.IncludeBannerInMails;
            model.Token = _ShoppingMailSettings.Token;
            model.UseDynamicTargeting = _ShoppingMailSettings.UseDynamicTargeting;
            model.UseSandbox = _ShoppingMailSettings.UseSandbox;

            return View("Nop.Plugin.Widgets.ShoppingMail.Views.WidgetsShoppingMail.Configure", model);
        }

        [HttpPost]
        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure(ConfigurationModel model)
        {
            if (!ModelState.IsValid)
                return Configure();

            //save settings
            _ShoppingMailSettings.IncludeBannerInMails = model.IncludeBannerInMails;
            _ShoppingMailSettings.Token = model.Token;
            _ShoppingMailSettings.UseDynamicTargeting = model.UseDynamicTargeting;
            _ShoppingMailSettings.UseSandbox = model.UseSandbox;

            _settingService.SaveSetting(_ShoppingMailSettings);

            return View("Nop.Plugin.Widgets.ShoppingMail.Views.WidgetsShoppingMail.Configure", model);
        }

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult ConfigureWidget(int widgetId)
        {
            var model = new WidgetConfigurationModel();
            if (widgetId > 0)
            {
                model.TrackingScript = _settingService.GetSettingByKey<string>(string.Format("Widgets.ShoppingMail.TrackingScript.{0}", widgetId));
            }
            else
            {
                model.TrackingScript = @"<!-- BEGIN Shoppingmail Tracking -->
<script type=""text/javascript"">
//<![CDATA[
document.write('<img src=""http://www.shopping-mail.com/service/track.php?
token={TOKEN}&amount={Order_Amount}&order_id={Order_id}"" />'); //]]>
</script>
<!-- END Shoppingmail Tracking -->";
            }

            return View("Nop.Plugin.Widgets.ShoppingMail.Views.WidgetsShoppingMail.ConfigureWidget", model);
        }

        [HttpPost]
        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult ConfigureWidget(int widgetId, WidgetConfigurationModel model)
        {
            if (!ModelState.IsValid)
                return ConfigureWidget(widgetId);
           
            _settingService.SetSetting(string.Format("Widgets.ShoppingMail.TrackingScript.{0}", widgetId), model.TrackingScript);

            return View("Nop.Plugin.Widgets.ShoppingMail.Views.WidgetsShoppingMail.ConfigureWidget", model);
        }

        [ChildActionOnly]
        public ActionResult PublicInfo(int widgetId)
        {
            string globalScript = "";
            var routeData = ((System.Web.UI.Page)this.HttpContext.CurrentHandler).RouteData;

            try
            {

                if (_ShoppingMailSettings.IncludeBannerInMails)
                {

                    if (routeData.Values["controller"].ToString().Equals("checkout", StringComparison.InvariantCultureIgnoreCase) &&
                        routeData.Values["action"].ToString().Equals("completed", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SWe are in last step of checkout, we can use order
                        Order lastOrder = GetLastOrder();

                        globalScript += GetTrackingScript(widgetId, lastOrder);
                    }
                   
                }


            }
            catch (Exception ex)
            {
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, "Error creating scripts for ShoppingMail", ex.ToString());
            }
            return Content(globalScript);
        }

        Order lastOrder = null;
        private Order GetLastOrder()
        {
            if (lastOrder == null)
            {
                var orders = _orderService.GetOrdersByCustomerId(_workContext.CurrentCustomer.Id);
                if (orders.Count != 0)
                {
                    lastOrder = orders[0];
                }
            }
            return lastOrder;
        }


        private string GetTrackingScript(int widgetId, Order order)
        {
            String totalFormated = "";
            if (order != null)
                totalFormated = order.OrderTotal.ToString("0", usCulture);
            else
                totalFormated = 0.ToString("0", usCulture);

            string shoppingMailConversionJS = _settingService.GetSettingByKey<string>(string.Format("Widgets.ShoppingMail.TrackingScript.{0}", widgetId)) + "\n";
            if (_ShoppingMailSettings.UseSandbox)
                shoppingMailConversionJS = shoppingMailConversionJS.Replace("{TOKEN}", "3aom9n45px4wggosow8sookooc4cwg0s44wos4gwc4ssgo4oso");
            else
                shoppingMailConversionJS = shoppingMailConversionJS.Replace("{TOKEN}", _ShoppingMailSettings.Token);
            shoppingMailConversionJS = shoppingMailConversionJS.Replace("{Order_Amount}", totalFormated);
            shoppingMailConversionJS = shoppingMailConversionJS.Replace("{Order_id}", order.Id.ToString());
            if (this.HttpContext.Request.Url.Scheme == "https")
                shoppingMailConversionJS = shoppingMailConversionJS.Replace("http://", "https://");

            return shoppingMailConversionJS;
        }




    }
}